
import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:study_demo/ui/game/liveable.dart';
import 'package:study_demo/ui/game/xy_game5/bullet.dart';

class HeroComponent extends SpriteAnimationComponent with HasGameRef, Liveable {
  HeroComponent() : super(size: Vector2(50, 37), anchor: Anchor.center);

  late Sprite bulletSprite;

  @override
  Future<void> onLoad() async {
    playing = false;
    List<Sprite> sprites = [];
    for (int i = 0; i <= 8; i++) {
      sprites.add(await Sprite.load('adventurer/adventurer-bow-0$i.png'));
    }
    animation =
        SpriteAnimation.spriteList(sprites, stepTime: 0.15, loop: false);
    animationTicker?.onComplete = _onLastFrame;
    position = gameRef.size / 2;

    bulletSprite = await gameRef.loadSprite('adventurer/weapon_arrow.png');

    initPaint(lifeColor: Colors.blue, lifePoint: 1000);
  }

  double speed = 200.0;

  @override
  void onGameResize(Vector2 gameSize) {
    super.onGameResize(gameSize);
    position.x = gameSize.x / 3;
  }

  void _onLastFrame() {
    animation!.createTicker().currentIndex = 0;
    animationTicker?.update(0);

    // 添加子弹
    Bullet bullet = Bullet(sprite: bulletSprite, maxRange: 200);
    bullet.size = Vector2(32, 32);
    bullet.anchor = Anchor.center;
    bullet.priority = 1;
    priority = 2;
    bullet.position = position - Vector2(0, -3);
    gameRef.add(bullet);
  }

  void flip({
    bool x = false,
    bool y = true,
  }) {
    scale = Vector2(scale.x * (y ? -1 : 1), scale.y * (x ? -1 : 1));
  }

  void shoot() {
    playing = true;
    animationTicker?.reset();
  }
}

class Monster extends SpriteAnimationComponent
    with CollisionCallbacks, Liveable {
  Monster({
    required SpriteAnimation animation,
    required Vector2 size,
    required Vector2 position,
  }) : super(
          animation: animation,
          size: size,
          position: position,
          anchor: Anchor.center,
        );

  @override
  Future<void> onLoad() async {
    add(RectangleHitbox()..debugMode = false);
    initPaint(lifeColor: Colors.redAccent, lifePoint: 1000);
  }

  @override
  void onCollision(Set<Vector2> intersectionPoints, PositionComponent other) {
    super.onCollision(intersectionPoints, other);
  }

  void move(Vector2 ds) {
    position.add(ds);
  }
}
